__author__ = 'guzhan.pc'
# coding:utf-8

import sys
import codecs
import os
import datetime
import time
import urllib.request
import logging
import EmailTools
import MyParser

# 排名不分先后 ん⊂（　＾ω＾）⊃
g_cvList = ['佐藤聡美', '喜多村英梨', '豊崎愛生', '杉田智和', '花澤香菜', '加藤英美里', '竹達彩奈', '井口裕香', '能登麻美子', '早見沙織']

# 获取网页的内容
def GetHttpContent(url):
    response = urllib.request.urlopen(url)
    html = response.read()
    return html.decode('utf-8')


# 获取今天使用的url地址
def GetTodayUrl():
    weekday = datetime.datetime.now().isoweekday()
    if weekday >= 6:
        # 双休日的节目表地址
        return 'http://agqr.jp/timetable/digital-ss.php'
    else:
        # 工作日的节目表地址
        return 'http://agqr.jp/timetable/digital-mf.php'

# 获取星级几的日文
def GetWeedDayInJapanese():
    weekdayInJapanese = ['月曜日', '火曜日', '水曜日', '木曜日', '金曜日', '土曜日', '日曜日']
    weekday = datetime.datetime.now().isoweekday()
    return weekdayInJapanese[weekday - 1]


# 创建要发送的文本
def CreateContentToSend(today, showList):
    result = '<h1>这个是今天(' + today + ')的节目列表</h1><br><h2>东京时间，需要-1h转换成北京时间</h2>'
    for show in showList:
        result += '时间：' + show.time + '&nbsp;&nbsp;&nbsp;'
        result += handleSomeShow(show.content)
        result += '<br>'
    return result


# 对自己感兴趣的cv节目加颜色更醒目
def handleSomeShow(content):
    for cv in g_cvList:
        if content.find(cv) >= 0:
            content = '<a href="http://www.uniqueradio.jp/agplayerf/newplayerf2-win.php" style=\'color:red;\'>' + content + '</a>'
            break
    return content

#　当前的节目是否需要提醒我
def NeedRemindMe(content):
    for cv in g_cvList:
        if content.find(cv) >= 0:
            return True
    return False

# 获取当前或者接下来的节目
# 如果当前节目不足10分针的话，就获取接下来的节目
def GetCurrentOrNextShow(hour, min, todayShowList):
    currentMins = hour * 60 + min
    for index in range(len(todayShowList)):
        # 第一个节目时间
        showTime = todayShowList[index].time.split(':')
        showHour = (int(showTime[0]) - 1 + 24) % 24  # 转换成北京时间
        showMin = int(showTime[1])
        showMins = showHour * 60 + showMin
        # 下一个节目时间
        nextShowMins = 0
        if index + 1 < len(todayShowList):
            nextShowTime = todayShowList[index + 1].time.split(':')
            nextShowHour = (int(nextShowTime[0]) - 1 + 24) % 24  # 转换成北京时间
            nextShowMin = int(nextShowTime[1])
            nextShowMins = nextShowHour * 60 + nextShowMin
        if currentMins > showMins and currentMins < nextShowMins:
            if nextShowMins - currentMins > 10: # 距离当前节目结束还大于10分钟，需要提醒
                return todayShowList[index], True
            else:
                return todayShowList[index + 1], False

# 保存为utf-8文件
def WriteFile(path, content):
    file_object = codecs.open(path, 'w', 'utf-8')
    file_object.write(content)
    file_object.close()

def ReadFile(path):
    file_object = codecs.open(path, 'r', 'utf-8')
    try:
        content = file_object.read()
    finally:
        file_object.close()
    return content


def InfoLog(content):
    logging.basicConfig(level=logging.INFO,
        format = '%(asctime)s %(message)s',
        datefmt = '%Y-%m-%d %H:%M:%S',
        filename = sys.path[0] + '\\myapp.log',
        filemode = 'a')
    logging.info(content)


# 每天第一次(凌晨4点之后)获取网页后保存在本地，以后从本地直接获取
try:
    currentTime = time.localtime()
    fileName = ''
    if currentTime[3] >= 4: # 凌晨3点后取当天
        fileName = '{0}-{1:02}-{2:02}.html'.format(currentTime[0], currentTime[1], currentTime[2])
    else:                   # 3点之前依然取前一天的
        fileName = '{0}-{1:02}-{2:02}.html'.format(currentTime[0], currentTime[1], currentTime[2] - 1)
    root = sys.path[0] + '\\html\\'
    filePath = root + fileName
    html_doc = ''
    isTodayFirst = False
    if os.path.exists(filePath):
        html_doc = ReadFile(filePath)
    else:
        html_doc = GetHttpContent(GetTodayUrl())
        WriteFile(filePath, html_doc)
        isTodayFirst = True
    allShows = MyParser.getAGAllShowList(html_doc)
    today = GetWeedDayInJapanese()
    todayShow = allShows.get(today)
    if isTodayFirst:
        email = CreateContentToSend(today, todayShow)
        EmailTools.SendEmail('flytopc@126.com', email)
    else:
        show, isCurrentShowing = GetCurrentOrNextShow(currentTime[3], currentTime[4], todayShow)
        if NeedRemindMe(show.content):
            email = ''
            if isCurrentShowing:
                email = '<h1>当前<a href="http://www.uniqueradio.jp/agplayerf/newplayerf2-win.php" style=\'color:red;\'>' + show.content + '</a>正在进行中。。。</h1>'
            else:
                email = '<h1>接下来<a href="http://www.uniqueradio.jp/agplayerf/newplayerf2-win.php" style=\'color:red;\'>' + show.content + '</a>即将开始。。。</h1>'
            EmailTools.SendEmail('flytopc@126.com', email)
    InfoLog('success!!!!')
except Exception as err:
    InfoLog('fail ' + str(err))